<template>
    <NavbarComponent />
    <div class="filter-page">
      <h1>商品筛选</h1>
      
      <!-- 筛选表单 -->
      <div class="filter-container">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="价格范围">
            <el-input-number 
              v-model="filters.minPrice"
              :min="0"
              :precision="2"
              placeholder="最低价"
            />
            <span class="price-separator">-</span>
            <el-input-number 
              v-model="filters.maxPrice"
              :min="0"
              :precision="2"
              placeholder="最高价"
            />
          </el-form-item>
  
          <el-form-item label="分类">
            <el-select
              v-model="filters.categories"
              multiple
              collapse-tags
              placeholder="选择分类"
              style="width:200px"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
  
          <el-form-item label="年级">
            <el-select
              v-model="filters.grade"
              clearable
              placeholder="选择年级"
              style="width:200px"
            >
              <el-option
                v-for="grade in gradeOptions"
                :key="grade"
                :label="grade"
                :value="grade"
              />
            </el-select>
          </el-form-item>
  
          <el-form-item label="专业">
            <el-autocomplete
              v-model="filters.major"
              :fetch-suggestions="searchMajors"
              placeholder="输入专业"
            />
          </el-form-item>
  <el-form-item label="学校">
    <el-autocomplete
      v-model="filters.school"
      :fetch-suggestions="searchSchools"
      placeholder="输入学校"
      @select="handleSelectSchool"
    />
  </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="applyFilters">筛选</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
  
      <!-- 商品展示区 -->
      <section class="products">
        <div v-if="loading" class="loading">
          <i class="el-icon-loading"></i> 加载中...
        </div>
        <div v-else-if="error" class="error">{{ error }}</div>
        <div v-else>
          <div class="product-grid">
            <div
              class="product-card"
              v-for="product in filteredProducts"
              :key="product.productId"
              @click="openProductDetail(product.productId)"
            >
              <div class="image-container">
                <img :src="'http://localhost:8092' + product.images" alt="商品图片" />
              </div>
              <div class="card-content">
                <h3 class="product-title">{{ product.productName }}</h3>
                <p class="product-description">{{ product.introduction }}</p>
                <div class="product-footer">
                  <span class="product-price">¥{{ product.price }}</span>
                  <span class="product-wants">{{ product.wants || 0 }}人想要</span>
                </div>
              </div>
            </div>
          </div>
          <div v-if="filteredProducts.length === 0" class="no-data">
            没有找到符合条件的商品
          </div>
        </div>
      </section>
      <RightSidebar />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import axios from 'axios'
  import NavbarComponent from '@/components/components/NavbarComponent.vue'
  import RightSidebar from '@/components/components/RightSidebar.vue'
  
  const router = useRouter()
  
  // 筛选条件
  const filters = ref({
    minPrice: null,
    maxPrice: null,
    categories: [],
    grade: '',
    major: '',
     school: ''
  })
  
  // 选项数据
  const categoryOptions = [
    '乐器','数码','艺术品','美妆','书籍',
    '服饰','家居','运动户外','文具','玩具','二手教材'
  ]
  const gradeOptions = ['大一','大二','大三','大四','研一','研二','研三']
  
  // 商品数据
  const filteredProducts = ref([])
  const loading = ref(false)
  const error = ref('')
  const searchSchools = async (query, cb) => {
  try {
    const response = await axios.get('http://localhost:8092/school/list', { 
      params: { keyword: query } 
    })
    // 根据实际接口返回数据结构调整
    const schools = response.data.map(s => ({
      value: s.schoolname // 根据实际返回字段调整
    }))
    cb(schools)
  } catch (err) {
    console.error('获取学校失败:', err)
    cb([])
  }
}

// 新增学校选择处理
const handleSelectSchool = (item) => {
  filters.value.school = item.value
}

  // 专业搜索建议
  const searchMajors = async (query, cb) => {
    try {
      const response = await axios.get('http://localhost:8092/major/list', { 
        params: { keyword: query } 
      })
      cb(response.data.map(m => ({ value: m })))
    } catch (err) {
      console.error('获取专业失败:', err)
      cb([])
    }
  }
  
  // 应用筛选
  const applyFilters = async () => {
    try {
      loading.value = true
      error.value = ''
      
      const params = {
        minPrice: filters.value.minPrice,
        maxPrice: filters.value.maxPrice,
        categories: filters.value.categories.join(','),
        grade: filters.value.grade,
        major: filters.value.major,
         school: filters.value.school
      }
  
      // 清理空值参数
      Object.keys(params).forEach(key => {
        if (!params[key] || params[key] === 'null') delete params[key]
      })
  
      const response = await axios.get('http://localhost:8092/product/filter', { params })
      
      if (response.data.code === 200) {
        filteredProducts.value = response.data.data || []
      } else {
        error.value = response.data.msg || '筛选失败'
      }
    } catch (err) {
      error.value = `请求失败：${err.message}`
      console.error('筛选失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  // 重置筛选
  const resetFilters = () => {
    filters.value = {
      minPrice: null,
      maxPrice: null,
      categories: [],
      grade: '',
      major: '',
      school: ''
    }
    filteredProducts.value = []
  }
  
  // 打开商品详情
  const openProductDetail = (productId) => {
    const routeData = router.resolve({
      path: '/product',
      query: { productId }
    })
    window.open(routeData.href, '_blank')
  }
  
  // 初始加载
  onMounted(() => {
    applyFilters()
  })
  </script>
  
  <style scoped>
  .filter-page {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
  }
  
  h1 {
    color: #2c3e50;
    border-bottom: 2px solid #f1c40f;
    padding-bottom: 10px;
    margin-bottom: 30px;
  }
  
  .filter-container {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    margin: 20px 0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  .filter-form {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .price-separator {
    margin: 0 8px;
    color: #606266;
  }
  
  /* 商品展示样式（与Category.vue保持一致） */
  .products {
    padding: 40px 20px;
  }
  
  .loading, .error, .no-data {
    text-align: center;
    font-size: 16px;
    padding: 40px 0;
  }
  
  .error {
    color: #e74c3c;
  }
  
  .product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 30px;
    padding: 20px;
  }
  
  .product-card {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
    overflow: hidden;
    cursor: pointer;
  }
  
  .product-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  }
  
  .image-container {
    width: 100%;
    height: 220px;
    overflow: hidden;
    position: relative;
  }
  
  .image-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }
  
  .product-card:hover img {
    transform: scale(1.05);
  }
  
  .card-content {
    padding: 18px;
  }
  
  .product-title {
    font-size: 16px;
    color: #34495e;
    margin: 0 0 12px;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
  
  .product-description {
    font-size: 14px;
    color: #7f8c8d;
    line-height: 1.5;
    margin: 0 0 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  
  .product-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .product-price {
    color: #ff5500;
    font-size: 18px;
    font-weight: bold;
  }
  
  .product-wants {
    color: #95a5a6;
    font-size: 13px;
  }
  
  @media (max-width: 768px) {
    .product-grid {
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      padding: 10px;
    }
    
    .image-container {
      height: 200px;
    }
    
    .filter-form {
      flex-direction: column;
    }
    
    .price-separator {
      margin: 5px 0;
      display: block;
      text-align: center;
    }
  }
  </style>